import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_colors.dart';

import 'package:mall/constant/app_strings.dart';
import 'package:mall/constant/text_style.dart';
import 'package:mall/gen/r.dart';
import 'package:mall/modules/model/fill_in_order_entity.dart';
import 'package:mall/modules/sc/fill_in_order_sc.dart';
import 'package:mall/modules/service/goods_service.dart';
import 'package:mall/ui/page/goods/widgets/goods_price_widget.dart';
import 'package:mall/ui/page/goods/widgets/order_goods_list_widget.dart';
import 'package:mall/ui/widgets/default_bg.dart';
import 'package:mall/ui/widgets/item_text.dart';
import 'package:mall/ui/widgets/right_arrow.dart';
import 'package:mall/utils/ext/widget_ext.dart';
import 'package:mall/utils/hud/hud_util.dart';
import 'package:mall/utils/image_component/image_component.dart';
import 'package:mall/utils/list_placeholder_component/list_placeholder_component.dart';
import 'package:mall/router/navigator_util.dart';

class FillInOrderPage extends StatefulWidget {
  FillInOrderPage();

  @override
  _FillInOrderPageState createState() => _FillInOrderPageState();
}

class _FillInOrderPageState extends State<FillInOrderPage> {
  // FillInOrderViewModel _fillInOrderViewModel = FillInOrderViewModel();
  TextEditingController _remarkController = TextEditingController();

  final sc_fillInOrder = Get.put(FillInOrderSc());

  @override
  void initState() {
    super.initState();
    // _fillInOrderViewModel.queryFillInOrderData(widget.cartId);
    sc_fillInOrder.cardId = Get.arguments['cartId'];
    sc_fillInOrder.refreshData();
  }

  @override
  Widget build(BuildContext context) {
    // return showWidget(_fillInOrderViewModel);
    return Obx(() => WrappedListPlaceholderComponent.widget1(
          state: sc_fillInOrder.loadState.value,
          data: sc_fillInOrder.data.value,
          builder: (p0) => _dataView(p0),
        ));
  }

  // Widget showWidget(FillInOrderViewModel fillInOrderViewModel) {
  //   if (fillInOrderViewModel.pageState == PageState.hasData) {
  //     return _dataView(fillInOrderViewModel);
  //   }
  //   return ViewModelStateWidget.stateWidgetWithCallBack(fillInOrderViewModel, () {});
  // }

  Widget _dataView(FillInOrderEntity model) {
    return APPScaffold(
      title: '提交订单',
      body: _contentView(model),
      bottomNavigationBar: _bottomWidget(model),
    );
  }

  Widget _contentView(FillInOrderEntity model) {
    return SingleChildScrollView(
      child: Container(
        width: MediaQuery.of(context).size.width,
        padding: EdgeInsets.only(left: 15, right: 15),
        child: Column(
          children: <Widget>[
            _addressWidget(model),
            SizedBox(height: 10),
            _goodsListWidget(model),
            SizedBox(height: 10),
            _remarkWidget(),
            SizedBox(height: 10),
            _couponWidget(model),
            SizedBox(height: 10),
            ItemTextView(AppStrings.GOODS_TOTAL, "${AppStrings.DOLLAR}${model.goodsTotalPrice}"),
            SizedBox(height: 10),
            ItemTextView(AppStrings.FREIGHT, "${AppStrings.DOLLAR}${model.freightPrice}"),
            SizedBox(height: 10),
            ItemTextView(AppStrings.COUPON_TOTAL, "${AppStrings.DOLLAR}${model.couponPrice}"),
          ],
        ),
      ),
    );
  }

  Container _goodsListWidget(FillInOrderEntity model) {
    return Container(
      padding: EdgeInsets.only(left: 15, right: 15, top: 10, bottom: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: OrderGoodsListWidget(checkedGoodsList: model.checkedGoodsList),
    );
  }

  //地址
  Widget _addressWidget(FillInOrderEntity model) {
    final address = model.checkedAddress;

    return Container(
      decoration: BoxDecoration(
        color: AppColors.C_FFFFFF,
        borderRadius: BorderRadius.all(Radius.circular(15)),
      ),
      height: 85,
      padding: EdgeInsets.all(15),
      child: address?.id != 0
          ? InkWell(
              onTap: () => _selectAddress(),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Text(address?.name ?? "", style: FMTextStyle.color_222222_size_13),
                            SizedBox(width: 5),
                            Text(address?.tel ?? "", style: FMTextStyle.color_222222_size_13),
                          ],
                        ),
                        SizedBox(height: 2),
                        Expanded(
                          child: Text(
                            (address?.province ?? "") +
                                (address?.city ?? "") +
                                (address?.county ?? "") +
                                (address?.addressDetail ?? ""),
                            style: FMTextStyle.color_222222_size_13,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 10),
                  Container(alignment: Alignment.centerRight, child: RightArrow())
                ],
              ),
            )
          : InkWell(
              //添加收货地址
              onTap: () => _selectAddress(),
              child: Container(
                child: Center(
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      ImageComponent(R.image.goodsBugAddAddress.path, size: 23),
                      SizedBox(width: 15),
                      Text('添加收货地址', style: TextStyle(color: AppColors.C_222222, fontSize: 18)),
                    ],
                  ),
                ),
              ),
            ),
    );
  }

  //优惠券
  Widget _couponWidget(FillInOrderEntity model) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        color: AppColors.C_FFFFFF,
      ),
      height: 45,
      padding: EdgeInsets.only(left: 15, right: 15),
      child: Row(
        children: <Widget>[
          //优惠券图片
          ImageComponent(
            R.image.coupon.path,
            size: 15,
          ),
          SizedBox(width: 5),
          Text(AppStrings.COUPON, style: FMTextStyle.color_222222_size_13),
          Expanded(
              child: Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                model.availableCouponLength == 0
                    ? Text(AppStrings.NOT_AVAILABLE_COUPON, style: FMTextStyle.color_999999_size_13)
                    : Text("${model.couponPrice}${AppStrings.MONEY_UNIT}", style: FMTextStyle.color_222222_size_13),
                Padding(
                  padding: EdgeInsets.only(left: 10),
                ),
                RightArrow()
              ],
            ),
          ))
        ],
      ),
    );
  }

  //备注
  Widget _remarkWidget() {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.C_FFFFFF,
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      // height: 75,
      padding: EdgeInsets.all(15),
      child: Row(
        children: <Widget>[
          Text(AppStrings.REMARK, style: FMTextStyle.color_222222_size_13),
          Expanded(
            child: Container(
              constraints: const BoxConstraints(
                maxHeight: 80.0,
                minHeight: 40.0,
              ),
              child: ExtendedTextField(
                maxLines: null,
                maxLength: 500,
                keyboardType: TextInputType.multiline,
                maxLengthEnforcement: MaxLengthEnforcement.enforced,
                controller: _remarkController,
                style: FMTextStyle.color_222222_size_13,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  counterText: '',
                  isDense: true,
                  hintText: '留言备注,可不填',
                  hintStyle: FMTextStyle.color_999999_size_13,
                  filled: true,
                  fillColor: Colors.transparent,
                  contentPadding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  //底部widget
  BottomAppBar _bottomWidget(FillInOrderEntity model) {
    return BottomAppBar(
        padding: EdgeInsets.zero,
        color: AppColors.C_FFFFFF,
        height: 60,
        child: Container(
          margin: EdgeInsets.only(left: 15, right: 15),
          child: Row(
            children: <Widget>[
              //总价
              GoodsPriceWidget(
                price: model.orderTotalPrice,
              ),
              Spacer(),

              //提交
              Container(
                alignment: Alignment.center,
                width: 118,
                height: 40,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(20)),
                  color: AppColors.C_FD2C55,
                ),
                child: Text(
                  '提交订单',
                  style: TextStyle(
                    color: AppColors.C_FFFFFF,
                    fontSize: 12,
                  ),
                ),
              ).onInkwellTap(() => _submitOrder(model)),
            ],
          ),
        ));
  }

  _submitOrder(FillInOrderEntity model) {
    if (model.checkedAddress?.id == null || model.checkedAddress?.id == 0) {
      HUDUtil.toast(AppStrings.PLEASE_SELECT_ADDRESS);
      return;
    }
    GoodsService.submitOrder(
      cartId: model.cartId.toString(),
      addressId: model.checkedAddress!.id.toString(),
      message: _remarkController.text,
      couponId: model.couponId.toString(),
    ).then((value) {
      NavigatorUtil.goSubmitSuccess(context);
    });

    // _fillInOrderViewModel
    //     .submitOrder(_fillInOrderViewModel.fillInOrderEntity.cartId, _fillInOrderViewModel.fillInOrderCheckAddress.id,
    //         _remarkController.value.toString(), _fillInOrderViewModel.fillInOrderEntity.couponId)
    //     .then((value) {
    //   if (value) {
    //     //https://www.jianshu.com/p/9d858596a30a
    //     /* Navigator.of(context).popUntil(
    //           (route) => route.settings.name.startsWith(Routers.goodsDetail));
    //     Navigator.pop(context);*/
    //     NavigatorUtil.goSubmitSuccess(context);
    //   }
    // });
  }

  _selectAddress() {
    NavigatorUtil.goAddress(callback: (p0) {
      sc_fillInOrder.updateAddress(p0);
    });
  }

  @override
  void dispose() {
    _remarkController.dispose();
    super.dispose();
  }
}
